<?php
namespace app\member\model;

use app\BaseModel;
use app\overlord\model\Active;
use app\shop\controller\IndexPayResunt;
use app\shop\model\IndexShopOrder;
use think\facade\Db;

class StoredOrder extends BaseModel
{
    //会员权益表
    protected $name = 'longbing_card_member_stored_order';


    /**
     * @author chenniang
     * @DataTime: 2020-09-17 17:47
     * @功能说明:订单详情
     */
    public function orderInfo($dis){

        $data = $this->where($dis)->find();

        return !empty($data)?$data->toArray():[];

    }

    /**
     * @author chenniang
     * @DataTime: 2020-09-11 10:29
     * @功能说明:下单
     */
    public function addOrder($stored,$user_id,$staff_id,$share_id){

        $member_model = new Member();

        $member_info  = $member_model->getMemberInfo(['user_id'=>$user_id,'uniacid'=>$stored['uniacid']]);

        $data = [

            'create_time' => time(),

            'status'      => 0,

            'user_id'     => $user_id,

            'staff_id'    => $staff_id,

            'stored_id'   => $stored['id'],

            'pay_price'   => round($stored['pay_price'],2),

            'true_price'  => round($stored['true_price'],2),

            'true_price_before' => round($member_info['stored'],2),

            'true_price_after'  => round($member_info['stored']+$stored['true_price'],2),

            'growth'      => $stored['growth'],

            'title'       => $stored['title'],

            'uniacid'     => $stored['uniacid'],

            'order_code'  => orderCode(),

            'type'        => $stored['stored_type'],

            'over_time'   => 0,

            'share_id'    => $share_id

        ];
        //如果是puls会员的，要把过期时间加好
        if($stored['stored_type']==1){

            $stored_level_model = new StoredLevel();

            $level = $stored_level_model->getLevel($stored['id']);

            if(empty($level)){

                return ['code'=>400,'msg'=>'等级未找到'];
            }

            $data['over_time'] = $level['over_time'];
        }

        $res = $this->insert($data);

        return $data;

    }


    /**
     * @author chenniang
     * @DataTime: 2020-09-17 13:48
     * @功能说明:订单退款时候处理储值
     */
    public function orderRefundStore($order_id,$app,$refund_prices){

        $order_model = new IndexShopOrder();

        $order_info  = $order_model->orderInfo(['id'=>$order_id]);
        //储值支付
        $reslut = new IndexPayResunt($app);
        //储值记录
        $res = $reslut->orderStoredResult($order_info,5,$refund_prices);

        return $res;
    }


    /**
     * @author chenniang
     * @DataTime: 2020-09-16 10:52
     * @功能说明:储值扣款
     */
    public function desStore($price,$text,$member_info,$controller_type,$controller,$order_code=0,$title=0){
        //注意:（3和5的order_code都是商城订单的order_code,其他的都是系统生成的）
        $order_code = !empty($order_code)?$order_code:orderCode();
        //4 是直接修改价格 1、2、3的是扣除 0、5充值是加,6是加 霸王餐优惠;7申请提现;8申请拒绝
        switch ($controller_type){

            case 0:
                $true_price_after = round($member_info['stored']+$price,2);
                break;

            case 1:
                $true_price_after = round($member_info['stored']-$price,2);
                break;

            case 2:
                $true_price_after = round($member_info['stored']-$price,2);
                break;

            case 3:
                $true_price_after = round($member_info['stored']-$price,2);
                break;

            case 4:
                $true_price_after = $price;
                break;

            case 5:
                $true_price_after = round($member_info['stored']+$price,2);
                break;

            case 6:
                $true_price_after = round($member_info['stored']+$price,2);
                break;

            case 7:
                $true_price_after = round($member_info['stored']-$price,2);
                break;

            case 8:
                $true_price_after = round($member_info['stored']+$price,2);
                break;

        }

        $data = [

            'create_time' => time(),

            'pay_time'    => time(),

            'status'      => 0,

            'user_id'     => $member_info['user_id'],

            'staff_id'    => in_array($controller_type,[1,4,6,7,8])?0:$controller,

            'stored_id'   => 0,

            'pay_price'   => round($price,2),

            'true_price'  => round($price,2),

            'true_price_before' => round($member_info['stored'],2),
            //4 是直接修改价格 2、3的是扣除 1充值是加
            'true_price_after'  => $true_price_after,

            'growth'      => 0,

            'title'       => $title,

            'uniacid'     => $member_info['uniacid'],

            'order_code'  => $order_code,

            'type'        => 0,

            'over_time'   => 0,

            'share_id'    => 0,

            'status'      => 2,

            'controller_type' => $controller_type,

            'controller'  => $controller,

            'text'        => $text

        ];

        $res = $this->insert($data);

        $id  = $this->getLastInsID();

        if($res==1){

            $member_model = new Member();

            if(in_array($controller_type,[4])){

                $y_price = $price;

            }elseif (in_array($controller_type,[1,2,3])){

                $y_price = $member_info['stored']-$price;

            }elseif (in_array($controller_type,[0,5])){

                $y_price = $member_info['stored']+$price;
            //霸王餐 优惠 管理员
            }elseif (in_array($controller_type,[6,8])){

                $y_price = $member_info['stored']+$price;

                $member_info['cash_stored'] +=$price;
            //提现 （霸王餐）
            }elseif (in_array($controller_type,[7])){

                $y_price = $member_info['stored']-$price;

                $member_info['cash_stored'] -=$price;

            }

            $where[] = ['id','=',$member_info['id']];

            $where[] = ['stored','>=',0];

            $res = $member_model->where($where)->update(['stored'=>$y_price,'cash_stored'=>$member_info['cash_stored']]);
            //目前只有员工扣款和后台扣款有佣金
            if(in_array($controller_type,[1,2])){

                $order = $this->orderInfo(['id'=>$id]);
                //配置模型
                $congfig = new Config();
                //返佣
                $congfig->controllerCommission($order);
            }

        }

        return $res;
    }







    /**
     * @author chenniang
     * @DataTime: 2020-09-11 10:59
     * @功能说明:回调
     */
    public function orderResult($order_code,$transaction_id){

        $order = $this->where(['order_code'=>$order_code])->find();

        if(empty($order_code)||$order->status!=0){

            return false;
        }

        $order = $order->toArray();
        //修改订单状态
        $this->where(['order_code'=>$order_code])->update(['status'=>2,'pay_time'=>time(),'transaction_id'=>$transaction_id]);
        //会员模型
        $member_model = new Member();
        //等级模型
        $level_model  = new Level();
        //获取用户会员信息(没有则创建)
        $user_info = $member_model->memberUpdateInfo(['user_id'=>$order['user_id'],'uniacid'=>$order['uniacid']]);
        //送储值
        $row['stored'] = $user_info['stored']+$order['true_price'];
        //0是普通会员，要送成长值
        if($order['type']==0){

            $row['growth'] = $user_info['growth']+$order['growth'];

            $growth_model = new Growth();

            $growth_model->addUserGrowth($order['uniacid'],$order['user_id'],$order['growth'],$order['id'],2,2);


        }else{
            //1是plus会员，给会员过期时间
            if($user_info['over_time']<time()){

                $time = strtotime("+".$order['over_time']."month");

                $row['over_time'] = $time;
                //赠送升级礼包
                //$level_model->upUserRights('999',$order);
            }
        }
        //编辑用户
        $level_model->upUserRightsEnd($row,$order);
        //返佣
        $config_model = new Config();

        $config_model->storeOrderCommission($order);

        $store_coupon = new StoredCoupon();

        $store_coupon->insertCoupon($order['stored_id'],$order['user_id'],$order['uniacid']);

        return true;
    }


    /**
     * @author chenniang
     * @DataTime: 2020-07-16 16:35
     * @功能说明:列表
     */
    public function recordList($dis,$page){

        $data = $this->where($dis)->order(['create_time desc','id desc'])->paginate($page)->toArray();

        if(!empty($data['data'])){

            foreach ($data['data'] as &$v){

                $v = $this->orderText($v['id']);

                $v['create_time'] = date('Y-m-d H:i:s',$v['create_time']);

            }

        }

        return $data;

    }


    /**
     * @author chenniang
     * @DataTime: 2020-09-27 14:33
     * @功能说明:拼接扣款文案
     */
    public function orderText($order_id){

        $v = $this->orderInfo(['id'=>$order_id]);

        //购买储值套餐
        if($v['controller_type']==0){

            $v['controller_avatar'] = lbUserAvatar($v['user_id']);

            $v['controller_name'] = '系统核算';

            $icon = $v['true_price']>0?'+':'-';

            $growth_add = $v['true_price']>0?$v['true_price']:$v['true_price']*-1;

            $boj    = $this->returnObj($v['type']);

            $v['admin_text'] = $boj.'【'.$v['title'].'】'.$icon.'¥'.$growth_add.',现余额 ¥'.$v['true_price_after'];

            $v['index_text'] = $boj.'【'.$v['title'].'】';

        }elseif($v['controller_type']==1){
            //后台扣款
            $v['controller_name'] = Db::name('longbing_admin')->where(['admin_id'=>$v['controller']])->value('account');

            $v['controller_avatar'] = 'https://retail.xiaochengxucms.com/defaultAvatar.png';

            $v['admin_text'] = '扣除储值 ¥'.$v['true_price'].',现储值 ¥'.$v['true_price_after'];

            $v['true_price'] = '-'.$v['true_price'];

            $v['index_text'] = '系统扣除储值';

        }elseif($v['controller_type']==2){
            //员工扣款
            $v['controller_avatar'] = lbUserAvatar($v['controller']);

            $v['controller_name']   = lbUserName($v['controller']);

            $v['admin_text'] = '扣除储值 ¥'.$v['true_price'].',现储值 ¥'.$v['true_price_after'];

            $v['true_price'] = '-'.$v['true_price'];

            $v['index_text'] = '员工扣除储值'.'【'.$v['controller_name'].'】';

        }elseif ($v['controller_type']==3){
            //购买套餐
            $v['controller_avatar'] = lbUserAvatar($v['user_id']);

            $v['controller_name']   = '系统核算';

            $growth_add = $v['true_price']>0?$v['true_price']:$v['true_price']*-1;

            $boj    = $this->returnObj($v['controller_type']);

            $v['admin_text'] = $boj.'【'.$v['title'].'】-¥'.$growth_add.',现余额 ¥'.$v['true_price_after'];

            $v['index_text'] = $boj.'【'.$v['title'].'】';

            $v['true_price'] = '-'.$v['true_price'];

        }elseif ($v['controller_type']==4){
            //员工修改
            $v['controller_name'] = Db::name('longbing_admin')->where(['admin_id'=>$v['controller']])->value('account');

            $v['controller_avatar'] = 'https://retail.xiaochengxucms.com/defaultAvatar.png';

            $v['admin_text'] = '储值 ¥'.$v['true_price_before'].',修改为 ¥'.$v['true_price_after'];

            $v['index_text'] = '系统修改储值';

        }elseif ($v['controller_type']==5){
            //购买商品退款
            $v['controller_avatar'] = lbUserAvatar($v['user_id']);

            $v['controller_name']   = '系统核算';

            $growth_add = $v['true_price']>0?$v['true_price']:$v['true_price']*-1;

            $boj    = $this->returnObj($v['controller_type']);

            $v['admin_text'] = $boj.'【'.$v['title'].'】+¥'.$growth_add.',现余额 ¥'.$v['true_price_after'];

            $v['index_text'] = $boj.'【'.$v['title'].'】';


        }elseif ($v['controller_type']==6){
            //霸王餐优惠
            $v['controller_avatar'] = lbUserAvatar($v['user_id']);

            $v['controller_name']   = is_numeric($v['controller'])?lbUserName($v['controller']):Db::name('longbing_admin')->where(['admin_id'=>$v['controller']])->value('account');;

            $growth_add = $v['true_price'];

            $boj        = $this->returnObj($v['controller_type']);

            $atv_model  = new Active();

            $title  = $atv_model->where(['id'=>$v['title']])->value('title');

            $v['admin_text'] = $boj.'【'.$title.'】'.'¥'.$growth_add.',现余额 ¥'.$v['true_price_after'];

            $v['index_text'] = $boj.'【'.$title.'】';

        }elseif ($v['controller_type']==7){
            //霸王餐优惠（提现）
            $v['controller_avatar'] = lbUserAvatar($v['user_id']);

            $v['controller_name']   = is_numeric($v['controller'])?lbUserName($v['controller']):Db::name('longbing_admin')->where(['admin_id'=>$v['controller']])->value('account');;

            $growth_add = $v['true_price'];

            $boj        = $this->returnObj($v['controller_type']);

            $v['admin_text'] = $boj.'-¥'.$growth_add.',现余额 ¥'.$v['true_price_after'];

            $v['true_price'] = '-'.$v['true_price'];

            $v['index_text'] = $boj;

        }elseif ($v['controller_type']==8){
            //霸王餐优惠（拒绝提现）
            $v['controller_avatar'] = lbUserAvatar($v['user_id']);

            $v['controller_name']   = Db::name('longbing_admin')->where(['admin_id'=>$v['controller']])->value('account');;

            $growth_add = $v['true_price'];

            $boj        = $this->returnObj($v['controller_type']);

            $v['admin_text'] = $boj.'¥'.$growth_add.',现余额 ¥'.$v['true_price_after'];

            $v['index_text'] = $boj;

        }

        return $v;

    }


    /**
     * @author chenniang
     * @DataTime: 2020-09-14 15:17
     * @功能说明:返回一个对象
     */
    public function returnObj($type){

        switch ($type){
            //购买会员商品
            case 0:
                return '购买套餐';

                break;
            //会员购买商品
            case 1:
                return '购买套餐';

                break;
            //购买储值套餐赠送
            case 2:
                return '购买储值套餐赠送';

                break;

            case 3:
                return '购买商品';

                break;

            case 5:
                return '商品退款';

                break;
            case 6:
                return '霸王餐活动';

                break;
            case 7:
                return '提现申请';

                break;
            case 8:
                return '拒绝提现';

                break;
            default:
                return '消费获得';

                break;
        }

    }










}